package com.bbs.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bbs.common.entity.Forum;
import com.bbs.common.entity.ForumCollect;
import com.bbs.common.exception.CommonException;
import com.bbs.common.mapper.ForumCollectMapper;
import com.bbs.common.mapper.ForumMapper;
import com.bbs.common.utils.RequestContextUtils;
import com.bbs.common.vo.ForumCollectListVo;
import com.bbs.common.vo.PageVo;
import com.bbs.dto.ForumCollectListDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * ForumCollectService
 *
 * @author yangjiajia
 * @since 2024/5/13 10:12
 */
@Service
public class ForumCollectService {

    @Autowired
    private ForumCollectMapper forumCollectMapper;

    @Autowired
    private ForumMapper forumMapper;

    /**
     * 帖子收藏或取消收藏
     **/
    @Transactional(rollbackFor = Exception.class)
    public int collect(int forumId) {
        int userId = RequestContextUtils.getUserId();
        Forum forum = forumMapper.selectById(forumId);
        if (forum == null) {
            throw new CommonException("帖子不存在");
        }
        if (forum.getDeleteFlag() == 1) {
            throw new CommonException("帖子已删除");
        }
        QueryWrapper<ForumCollect> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ForumCollect::getForumId, forumId).eq(ForumCollect::getUserId, userId);
        if (forumCollectMapper.exists(queryWrapper)) {
            //取消收藏
            forumCollectMapper.delete(queryWrapper);
            forum.setCollects(forum.getCollects() - 1);
            forumMapper.updateById(forum);
        } else {
            //收藏
            ForumCollect collect = new ForumCollect();
            collect.setForumId(forumId);
            collect.setUserId(userId);
            collect.setCreateTime(LocalDateTime.now());
            forumCollectMapper.insert(collect);
            forum.setCollects(forum.getCollects() + 1);
            forumMapper.updateById(forum);
        }
        return forum.getCollects();
    }

    /**
     * 我的收藏
     **/
    public PageVo<ForumCollectListVo> list(ForumCollectListDTO listDTO) {
        int userId = RequestContextUtils.getUserId();
        Page<ForumCollect> queryPage = new Page<>(listDTO.getPage(), listDTO.getPageSize());
        IPage page = forumCollectMapper.list(queryPage, userId, listDTO.getTitle());
        return new PageVo<>(page);
    }
}
